package com.yifang.yibingproject.utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.time.Duration;
import java.util.Set;

/**
 * Redis工具类
 *
 * @author Lew
 * @create in 2019/6/17 13:06
 */
@Component
public class RedisUtils {
    private static RedisTemplate<String, String> redisTemplate;

    private static RedisTemplate<String, Object> objectRedisTemplate;

    @Autowired
    public void setRedisTemplate(RedisTemplate<String, String> redisTemplate) {
        RedisUtils.redisTemplate = redisTemplate;
    }

    @Autowired
    public void setObjectRedisTemplate(RedisTemplate<String, Object> objectRedisTemplate) {
        RedisUtils.objectRedisTemplate = objectRedisTemplate;
    }

    /**
     * 保存字符串，指定过期时长
     *
     * @param k
     * @param v
     * @param duration
     */
    public static void setStr(String k, String v, Duration duration) {
        redisTemplate.opsForValue().set(k, v, duration);
    }


    /**
     * @param k
     * @return 返回Redis中是否存在指定的key
     */
    public static boolean hasStrKey(String k) {
        return redisTemplate.hasKey(k);
    }

    /**
     * @param k
     * @return 返回指定键的字符串，不存在或者已过期返回null
     */
    public static String getStr(String k) {
        return redisTemplate.opsForValue().get(k);
    }

    /**
     * 保存对象，指定过期时长
     *
     * @param k
     * @param v
     * @param duration
     */
    public static void setObj(String k, Object v, Duration duration) {
        objectRedisTemplate.opsForValue().set(k, v, duration);
    }

    /**
     * @param k
     * @return 返回指定键的对象，不存在或者已过期返回null
     */
    public static Object getObj(String k) {
        return objectRedisTemplate.opsForValue().get(k);
    }


    /**
     * 删除指定key
     *
     * @param k
     * @return
     */
    public static Boolean delete(String k) {
        return redisTemplate.delete(k);
    }

    /**
     * 删除指定匹配格式的键
     * @param pattern
     * @return
     */
    public static Long deleteByPattern(String pattern){
        Set<String> keys = redisTemplate.keys(pattern);
        return redisTemplate.delete(keys);
    }
}
